package com.roy.minimq.broker.application;

import com.roy.minimq.common.broker.BrokerConfig;
import com.roy.minimq.remoting.domain.nettyclient.NettyClientConfig;
import com.roy.minimq.remoting.domain.nettyserver.NettyServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BrokerStartup {
    private static Logger logger = LoggerFactory.getLogger(BrokerStartup.class);
    public static void main(String[] args) {
        BrokerController controller = createController();
        logger.info("broker controller created");
        start(controller);
        logger.info("broker server started at port " );
    }

    public static BrokerController createController(){
        final BrokerConfig brokerConfig = getBrokerConfig();

        final NettyServerConfig nettyServerConfig = new NettyServerConfig();
        final NettyClientConfig nettyClientConfig = new NettyClientConfig();
        return new BrokerController(brokerConfig,nettyServerConfig,nettyClientConfig);
    }

    //TODO 测试用。真实环境下这些配置需要从配置文件中加载。
    private static BrokerConfig getBrokerConfig(){
        BrokerConfig brokerConfig = new BrokerConfig();
        //TODO 测试用。真实环境下这些配置需要从配置文件中加载。
        brokerConfig.setBrokerId(1L);
        brokerConfig.setBrokerClusterName("ClusterTest");
        brokerConfig.setBrokerName("brokerA");
        brokerConfig.setNamesrvAddr("127.0.0.1:9876");
        return brokerConfig;
    }

    public static void start(BrokerController controller){
        boolean initResult = controller.initialize();
        if (!initResult) {
            controller.shutdown();
            System.exit(-3);
        }
        //服务关闭钩子
//        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
//            private volatile boolean hasShutdown = false;
//            private AtomicInteger shutdownTimes = new AtomicInteger(0);
//
//            @Override
//            public void run() {
//                synchronized (this) {
//                    logger.info("Shutdown hook was invoked, {}", this.shutdownTimes.incrementAndGet());
//                    if (!this.hasShutdown) {
//                        this.hasShutdown = true;
//                        long beginTime = System.currentTimeMillis();
//                        controller.shutdown();
//                        long consumingTimeTotal = System.currentTimeMillis() - beginTime;
//                        logger.info("Shutdown hook over, consuming total time(ms): {}", consumingTimeTotal);
//                    }
//                }
//            }
//        }
//        ,"BrokerShutDownHookThread"));
        //启动服务
        controller.start();
    }
}
